import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_shipper/AppConfig/ShowDialog.dart';
import 'package:sph_shipper/Order/WaybillDetails/ViewAgreementView.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';

class ElectronicAgreementView extends StatefulWidget {
  const ElectronicAgreementView({super.key, required this.dataList, required this.waybillId});
  final List dataList;
  final String waybillId;
  @override
  State<ElectronicAgreementView> createState() => _ElectronicAgreementViewState();
}

class _ElectronicAgreementViewState extends State<ElectronicAgreementView> {
  String emailStr="";

  //获取电子协议内容
  Future<void> getContractLogMessage(String waybillContractId) async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/waybill/waybill/common/getWaybillContractOne',
      data: {
        "waybillContractId":waybillContractId,
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) {
                return ViewAgreementView(url: jsonMap['data']['contractPath'],);
              }));
        } else {
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  Future<void> sendWaybillContract() async {
    LoadingDialog.show(context);
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header + 'api/waybill/waybill/common/sendWaybillContract',
      data: {
       "waybillId":widget.waybillId,
        "mailAddress":emailStr,
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          LoadingDialog.hide(context);
          BrnToast.show("提交成功", context);
        } else {
          LoadingDialog.hide(context);
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  bool isEmailValid(String email) {
    // 定义邮箱地址的正则表达式
    RegExp emailRegExp = RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$');

    // 使用正则表达式匹配邮箱地址
    return emailRegExp.hasMatch(email);
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text("电子协议",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        centerTitle: true,
        actions: [
          GestureDetector(
            child: Text("投诉",style: TextStyle(color: Colors.black),),
            onTap: (){},
          ),
          Badge(label: Text("1"),),
        ],
      ),
      body: Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                height: widget.dataList.length * 50.h,
                child:ListView.builder(
                    shrinkWrap:false,
                    itemCount:widget.dataList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return GestureDetector(
                        child: Container(
                          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                          padding: EdgeInsets.only(top: 6.h,bottom: 6.h,left: 12.w,right: 4.w),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            color: Colors.white,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Image.asset("lib/Images/OrderList/电子协议icon.png",width: 26.w,height: 26.h,),
                                  SizedBox(width: 7.w,),

                                  Text(widget.dataList[index]["effectiveStatus"]==0? "货物运输交易协议":"货物运输交易协议(已作废)",style: TextStyle(color: Colors.black),),
                                ],
                              ),
                              Row(
                                children: [
                                  Text("查看",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                  SizedBox(width: 3.w,),
                                  Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 20,),
                                ],
                              ),
                            ],
                          ),
                        ),
                        onTap: (){

                          getContractLogMessage(widget.dataList[index]['id']);
                        },
                      );}),
              ),
              SizedBox(height: 26.h,),
              Text("       "+"输入邮箱，将以上所有电子协议发送至邮箱",style: TextStyle(fontSize: 13.sp,color: MyColors.textColor),),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                  padding: EdgeInsets.only(top: 12.h,bottom: 12.h,left: 11.w,right: 4.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                    color: Colors.white,
                  ),
                  child: Row(
                    children: [
                      Text("电子邮箱",style: TextStyle(color: Colors.black),),
                      SizedBox(width: 18.w,),
                      Container(
                        width: 200.w,
                        height: 20.h,
                        color: MyColors.backgreyColor,
                        child:  TextField(
                          decoration: InputDecoration(
                            hintText: '请输入您的邮箱地址',
                            hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                            filled: true,
                            fillColor: Colors.white,
                            border: InputBorder.none,
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                          ),
                          keyboardType: TextInputType.number,
                          textAlign: TextAlign.left,
                          style: TextStyle(color: Colors.black,fontSize: 14.sp),
                          onChanged: (value) {
                            setState(() {

                                emailStr=value;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          ),
          Container(
            height: 85.h,
            color: Colors.white,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top:10.h,bottom:40.h ),
            child: BrnSmallMainButton(
              title: '发送至邮箱',
              bgColor:emailStr==""? Color.fromRGBO(223, 223, 223, 1):MyColors.themeColor,
              radius: 30,
              fontSize: 16.sp,
              width: screenSize.width-30.w,
              onTap: () {
                if (isEmailValid(emailStr)) {
                  sendWaybillContract();
                } else {
                  BrnToast.show("请输入正确格式的邮箱", context);
                }
              },
            ),
          ),
        ],
      )


    );
  }
}
